package com.yirui.bridge.controller;

import com.yirui.bridge.annotation.SourceType;
import com.yirui.bridge.core.Server;
import com.yirui.bridge.core.ServerManager;
import com.yirui.bridge.udp.NettyUdpClient;
import com.yirui.bridge.util.HexCodec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Dujie
 * @create 2021/11/3
 * @since 1.0.0
 */
@RestController
@RequestMapping("/udp")
@SourceType("udp")
public class UdpController {
    @Autowired
    private ServerManager serverManager;

    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    /**
     * 获取设备状态
     * @return
     */
    @RequestMapping("/status")
    public Server getStatus() throws Exception {
        return serverManager.getServer();
    }

    /**
     * 发送操作指令
     * @return
     */
    @RequestMapping("/send")
    public Map send(@RequestParam(value="value") String value){
        Map res = new HashMap();
        try {
            NettyUdpClient nettyClient = (NettyUdpClient) serverManager.getServer();
            if(nettyClient == null || nettyClient.getChannel() == null){
                res.put("success", false);
                res.put("error", "服务未启动");
                res.put("status",nettyClient==null?"对象是空的":nettyClient.getReceiveData());
            }else {
                nettyClient.getReceiveData().set(false);
                nettyClient.send(HexCodec.encode(value));

                //防止会话过期
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if(!nettyClient.getReceiveData().get()){
                            //发送会话检查
                            nettyClient.send(nettyClient.getSessionId());
                            nettyClient.send(HexCodec.encode(value));
                        }

                    }
                });
                res.put("success", true);
                res.put("lastSentValue", value);
                res.put("res", nettyClient.getRes());
                res.put("msg", "ok");


            }
        }catch (Exception ex){
            res.put("success", false);
            res.put("error", ex.toString());
        }
        return res;
    }
}
